package thread;

/**
 * @author: 成金乘
 * @date: 2022/12/20 15:23
 * @description:
 */
//编写代码, 实现线程安全版本的单例模式
class Singleton{
    //创建实例,volatile修饰保证线程有序性
    private volatile static Singleton instance = null;
    private Singleton(){}
    //获取实例
    public static Singleton getInstance(){
        //双重if防止线程多次加锁,避免不必要的开销
        if (instance == null){
            synchronized (Singleton.class){
                //加锁后确定没有实例化再进行实例化
                if (instance == null){
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}
public class ThreadDemo9 {
    public static void main(String[] args) {
        Singleton s1 = Singleton.getInstance();
        Singleton s2 = Singleton.getInstance();
        System.out.println(s1 == s2);
    }
}
